package com.yueyang.sojourn.server.common.baymax.web.resolver.spi.imp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yueyang.sojourn.server.common.baymax.web.resolver.RestResponseMessage;
import com.yueyang.sojourn.server.common.baymax.web.resolver.spi.RestResponseMessageProvider;
import feign.FeignException;

/**
 * spi 远程调用抛出的异常
 */
public class SpiRemoteCallExceptionRestResponseMessageProvider
        implements RestResponseMessageProvider {
//  /**
//   * 是否是spi调用异常
//   */
//  private final boolean spiCallExceptionPresent =
//      ClassUtils.isPresent("com.yueyang.sojourn.server.common.hiro.feign.invocation.exception.RemoteBizCodeSupport",
//          this.getClass().getClassLoader());

//  @Override
//  public boolean support(Exception source) {
//    // check source or cause (null return false)
//    return spiCallExceptionPresent && (source instanceof RemoteBizCodeSupport
//        || source.getCause() instanceof RemoteBizCodeSupport);
//  }

    @Override
    public boolean support(Exception source) {
        // check source or cause (null return false)
        return (source instanceof FeignException
                || source.getCause() instanceof FeignException);
    }

//  @Override
//  public RestResponseMessage produce(Exception source) {
//     ex = RemoteBizCodeSupport.class
//        .cast(source instanceof RemoteBizCodeSupport ? source : source.getCause());
//
//    RestResponseMessage message =
//        new RestResponseMessage(ex.getBizCode(), ex.getBizMessage(), ex.isValidResponseStatus()
//            ? ex.getResponseStatus() : HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
//
//    message.setRequestSucceeded(ex.isValidResponseStatus());
//    return message;
//  }

    @Override
    public RestResponseMessage produce(Exception source) {
        FeignException ex = FeignException.class
                .cast(source instanceof FeignException ? source : source.getCause());
        JSONObject jsonObject = JSON.parseObject(new String(ex.content()));
        RestResponseMessage message =
                new RestResponseMessage(jsonObject.getInteger("code"), jsonObject.getString("message"), ex.status());

//    message.setRequestSucceeded(ex.isValidResponseStatus());
        return message;
    }

}
